package com.brrbaii.controller;
import cn.hutool.core.bean.BeanUtil;
import com.brrbaii.Exception.BusinessException;
import com.brrbaii.common.BaseResponse;
import com.brrbaii.common.ErrorCode;
import com.brrbaii.model.dto.UserQueryDTO;
import com.brrbaii.model.entity.User;
import com.brrbaii.model.dto.UserLoginDTO;
import com.brrbaii.model.dto.UserRegisterDTO;
import com.brrbaii.model.vo.UserVO;
import com.brrbaii.service.UserService;
import com.brrbaii.utils.ResultUtils;
import com.brrbaii.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.brrbaii.common.StrConstants.USER_LOGIN_STATE;


@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;


    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterDTO userRegisterDTO){
        if (userRegisterDTO == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        String username = userRegisterDTO.getUsername();
        String userPassword = userRegisterDTO.getUserPassword();
        String checkPassword = userRegisterDTO.getCheckPassword();
        long userId = userService.userRegister(username, userPassword, checkPassword);
        return ResultUtils.success(userId);
    }

    @PostMapping("/login")
    public BaseResponse<UserVO> userLogin(@RequestBody UserLoginDTO userLoginDTO, HttpServletRequest request){
        if (userLoginDTO == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String username = userLoginDTO.getUsername();
        String userPassword = userLoginDTO.getUserPassword();

        if (StringUtils.isAnyBlank(username,userPassword)){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User user = userService.userLogin(username, userPassword, request);
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user,userVO);
        return ResultUtils.success(userVO);
    }

    @PostMapping("/logout")
    public BaseResponse userLogout(HttpServletRequest request){
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return ResultUtils.success();
    }

    @PostMapping("/search")
    public BaseResponse<List<UserVO>> searchList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "5") Integer pageSize,
            @RequestBody(required = false) UserQueryDTO userQueryDTO
    ){

        List<User> users = userService.queryUserByName(userQueryDTO);
        List<UserVO> usersVO = users.stream().map(
                user -> {
                    UserVO userVO = new UserVO();
                    BeanUtil.copyProperties(user, userVO);
                    return userVO;
                }
        ).collect(Collectors.toList());
        return ResultUtils.success(usersVO);

    }

    @DeleteMapping("/delete/{id}")
    public BaseResponse<Boolean> deleteUser(@PathVariable("id") long id){
        boolean result = userService.deleteUserById(id);
        return ResultUtils.success(result);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUserYupi(@RequestBody long id){
        boolean result = userService.deleteUserById(id);
        return ResultUtils.success(result);
    }


    /**
     * 获取用户状态
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<UserVO> getCurrentUser(){
        User currentUser = UserHolder.getUser();
        if(currentUser == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        //用户信息可能频繁变动，直接从session里拿不恰当，重新查库获取最新的用户信息
        Long userId = currentUser.getId();
        //todo 校验用户是否合法
        User latelyUser = userService.getById(userId);
        //脱敏
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(latelyUser,userVO);
        return ResultUtils.success(userVO);
    }




}
